<!-- 订阅文章 -->
<template>
  <span>
    <el-dialog
      :visible.sync="selectImgDialogVisible"
      width="90%"
      style="height: 100%;"
      title="订阅文章"
      :z-index="1003"
      modal-append-to-body
      :close-on-click-modal="false"
      class="editAllImagedialog"
    >
    <div class="fill-width-height dialog-content flex-col">
      <el-divider style="margin: 0"/>
      <el-row :gutter="12" class="fill-height flex-1 overflow-hidden" style="margin:0;min-height: 0;">
        <el-col :span="24" :xs="6" :sm="6" :md="8" :lg="8" class="fill-height flex-col">
          <div class="flex-row" style="padding: 10px;">
            <el-button size="small" type="primary" @click="addTask">添加</el-button>
            <el-button size="small" type="success" @click="restCrawerSubscribeDetail">爬取内容</el-button>
            <el-button size="small" type="info" @click="() => getPage()">刷新</el-button>
            <el-button size="small" type="danger" @click="handleDelete">删除</el-button>
          </div>
          <el-divider/>

          <el-tabs v-model="activeName" @tab-click="handleClick" class="flex-1 overflow-hidden" style="overflow: hidden;">
            <el-tab-pane :label="item.authorname" :name="item.authorname" class="fill-height" v-for="(item,index) in typeList" :key="index">
              <div class="min-height-0 fill-height" style="overflow: auto;min-height: 0;">
                <el-card :body-style="{ padding: '0px' }" v-for="(item,index) in tableDataList" :key="index"
                         @click.native="itemCard(item)" style="cursor: pointer;margin: 8px 5px;"
                >
                  <div class="flex-row flex-wrap position-relative">
                    <div class="fill-height" style="padding: 5px;">
                      <img :src="item.coverimageurl" class="image" alt="" style="width: 60px;">
                    </div>
                    <div class="fill-height flex-1">
                      <div style="padding: 14px;">
                        <div class="bottom clearfix">
                          公众号：<time class="time">{{ item.authorname }}</time>
                        </div>
                        <span>合集名称：<span>{{ item.tagname }}</span></span>
                        <el-tag v-if="item.taskstatus" :type="item.taskstatus !== '爬取完成' ? 'warning' : 'success'" style="margin-left: 5px;">
                          {{ item.taskstatus }}
                        </el-tag>
                      </div>
                       <el-checkbox
                         v-model="item.selected"
                         class="position-absolute"
                         style="top: 5px;right: 10px;"
                       ></el-checkbox>
                    </div>
                  </div>
                </el-card>
              </div>

            </el-tab-pane>
          </el-tabs>
         <el-divider/>
          <div style="height: 10px;"></div>
         <pagination
           small
           :total="total"
           :page.sync="queryParams.pageNum"
           :limit.sync="queryParams.pageSize"
           @pagination="getPage"
           :page-sizes="[50, 100, 200, 500]"
           style="margin: 0 !important; padding: 0 !important;"
         />
        </el-col>
        <el-col :span="24" :xs="18" :sm="18" :md="16" :lg="16" class="fill-height flex-col">
          <div class="d-flex align-center" style="margin-top: 10px;">
             <el-button size="small" type="primary" @click="startCrawerSubscribeDetail">开始爬取</el-button>
            ·<el-button type="danger" size="small" @click="handleDeleteArticles">删除</el-button>
          </div>
          <div class="detail-list flex-1 overflow-auto">
            <el-card v-for="(item, index) in detailDataList" :key="index" class="detail-item" style="cursor: pointer">
              <div class="fill-width flex-col">
                <div class="flex-row gap-10 fill-width align-center justify-center">
                  <el-checkbox v-model="item.selected"></el-checkbox>
                  <span>{{ item.seqindex }}.{{ item.title }}</span>
                  <div class="flex-1" style="margin-left: 5px;">
                    <el-tag type="info" v-if="item.iscrawled == 0">未爬取</el-tag>
                    <el-tag type="success" v-if="item.iscrawled == 1">已爬取</el-tag>
                  </div>
                  <div>
                     <el-button type="text" class="button" @click.stop="copyPath(item)" style="color:#4CAF50;margin-left: 10px">复制</el-button>
                  </div>
                </div>
               <div class="url flex-1">{{ item.url }}</div>
              </div>
            </el-card>
          </div>
        </el-col>
     </el-row>
    </div>
  </el-dialog>

  <ItemForm ref="itemFormRef" :args="args" @callBack="() => getPage()"/>
  </span>
</template>
<script>
import {
  getDetailList,
  deleteByIds,
  getPage,
  detailDeleteByIds,
  startCrawerSubscribe,
  startCrawerSubscribeDetailById, restCrawerSubscribeDetailById, getSubscribeArticlesTypeList
} from '@/api/imgManage/subscribeArticles'

export default {
  name: '',
  components: {
    ItemForm: () => import('./itemForm')
  },
  props: {},
  data() {
    return {
      selectImgDialogVisible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 12
      },
      total: 0,
      tableDataList: [],
      args: {
        mode: '',
        formId: ''
      },
      detailDataList: [],

      typeList: [],
      activeName: '全部'
    }
  },
  computed: {},
  methods: {
    handleClick(){
      this.getPage();
    },
    async getTypeList(){
      const typeList = await getSubscribeArticlesTypeList().then(res => res.data)
      this.typeList = [{
        authorname: '全部'
      }]
      this.typeList.push(...typeList)
      await this.getPage();
    },

    async startCrawerSubscribeDetail() {
      const ids = this.detailDataList.filter(item => item.selected).map(item => item.id)
      if (ids.length !== 1) {
        return this.$message.warning('只能选择一条数据')
      }
      const id = ids[0]
      try {
        this.$modal.loading('正在处理，请稍候...')
        await startCrawerSubscribeDetailById({ id: id })
        this.$message.success('提交爬取任务成功！')
        this.$modal.closeLoading()

      } catch (error) {
        console.error('爬取失败:', error)
        this.$modal.closeLoading()
      }
    },
    async copyPath(item) {
      const imageSrc = item.url
      try {
        await navigator.clipboard.writeText(imageSrc)
        this.$message.success('复制成功')
      } catch (error) {
        console.error('复制失败:', error)
      }
    },
    addTask() {
      this.args.mode = 'add'
      this.$refs.itemFormRef.init()
    },
    async restCrawerSubscribeDetail(){
      try {
        const selectedIds = this.tableDataList
          .filter(item => item.selected)
          .map(item => item.id)
        if (selectedIds.length != 1) {
          return this.$message.warning('只能选择一条数据')
        }
        await this.$confirm(
          '确认重新爬取这个合集的所有文章地址吗？',
          '确认爬取',
          { type: 'warning' }
        )
        const id = selectedIds[0]

        await restCrawerSubscribeDetailById({ id: id })
        this.$message.success('爬取成功')
        await this.getPage()
      } catch (error) {
        this.$message.error('爬取失败')
      }
    },
    async startCrawerSubscribe() {
      try {
        const selectedIds = this.tableDataList
          .filter(item => item.selected)
          .map(item => item.id)
        if (selectedIds.length != 1) {
          return this.$message.warning('只能选择一条数据')
        }

        await this.$confirm(
          '确认爬取该合集中的所有文章里的图？',
          '确认爬取',
          { type: 'warning' }
        )
        const id = selectedIds[0]

        await startCrawerSubscribe({ id: id })
        this.$message.success('爬取成功')
        await this.getPage()
      } catch (error) {
        this.$message.error('爬取失败')
      }
    },
    async handleDelete() {
      const selectedIds = this.tableDataList
        .filter(item => item.selected)
        .map(item => item.id)
      if (!selectedIds.length) {
        return this.$message.warning('请选择要删除的订阅')
      }
      await this.$confirm(
        '确认爬取该合集吗？',
        '确认删除',
        { type: 'warning' }
      )
      try {
        await deleteByIds({ids: selectedIds.join(',')})
        this.$message.success('删除成功')
        await this.getPage()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    async handleDeleteArticles() {
      try {
        const selectedArticles = this.detailDataList.map(item => item.id).join(',')
        await this.$confirm(
          '确认删除选中的文章？',
          '删除确认',
          { type: 'warning' }
        )

        await detailDeleteByIds({
          ids: selectedArticles
        })

        this.$message.success('文章删除成功')
        const getDetailList = this.detailDataList[0].subscribearticlesid
        this.getDetailList(getDetailList)
      } catch (error) {
      }
    },
    init() {
      this.selectImgDialogVisible = true
      this.getTypeList()
    },
    itemCard(item) {
      this.tableDataList.forEach(items => items.selected = false)
      item.selected = true

      this.getDetailList(item.id)
    },
    async getPage() {
      this.tableDataList = []
      const res = await getPage(Object.assign(this.queryParams,{ 'authorname': this.activeName }))
      this.tableDataList = res.rows
      this.total = res.total
    },
    async getDetailList(subscribearticlesid) {
      this.detailDataList = []
      const res = await getDetailList({ subscribearticlesid: subscribearticlesid })
      this.detailDataList = res.data
    }
  },
  mounted() {

  }
}
</script>


<style lang="scss">
.editAllImagedialog {
  .el-dialog {
    height: 90% !important;
  }

  .el-dialog__body {
    height: calc(100% - 54px);
    padding: 10px;
  }

  .detail-item {
    padding: 12px;
    margin: 8px;
  }
}
</style>

<style scoped lang="scss">
::v-deep {
  .el-tabs__content{
    height: calc(100% - 40px);
  }
  .el-tabs__header{
    margin: 0;
  }
}
</style>
